#include "mystdio.h"

myFILE* my_fopen(const char* path, const char* mode)
{
    int fd = 0;
    int flags = 0;
    if(strcmp(mode, "r") == 0)
        flags |= O_RDONLY;
    else if(strcmp(mode, "w") == 0)
        flags |= (O_WRONLY | O_TRUNC | O_CREAT);
    else if(strcmp(mode, "a") == 0)
        flags |= (O_APPEND | O_WRONLY | O_CREAT);
    
    if(flags | O_TRUNC)
        fd = open(path, flags, DFL_MODE);
    else fd = open(path, flags);
    
    if(fd < 0)
    {
        errno = 2;
        return NULL;
    }

    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));//自定义类型要加()
    if(fp == NULL)
    {
        errno = 3;
        return NULL;
    }

    fp->fileno = fd;
    fp->flag = FFLUSH_LINE;
    fp->end = 0;
    return fp;
}

int my_fwrite(const char* str, int num, myFILE* stream)
{
    memcpy(stream->buffer + stream->end, str, num);
    //stream->end += num;

    // 判断是否需要刷新, "abcd\nefgh"
    //if((stream->flag & FFLUSH_LINE) && stream->end > 0 && stream->buffer[stream->end-1] == '\n')
    //{
    //    my_fflush(stream);
    //}
    int last_end = 0;//geshu
    if((stream->flag & FFLUSH_LINE) && (num > 0))//问题在这，个数用num
        for(size_t i = stream->end; i < stream->end + num; i++)
           // if(stream->buffer[i] == '\\' && stream->buffer[i + 1] == 'n')
            if(stream->buffer[i] == '\n')
                last_end = i + 1;
    printf("%d\n", last_end);
    stream->end = stream->end + num - last_end;
    printf("%s\n\n", stream->buffer);
    if(last_end)
    {
        write(stream->fileno, stream->buffer, last_end);
        memmove(stream->buffer, stream->buffer + last_end, stream->end);
    }
    return 0;
}

int my_fflush(myFILE* stream)
{
    if(stream->end > 0)
    {
        write(stream->fileno, stream->buffer, stream->end);
        stream->end = 0;
    }
    return 0;
}

int my_fclose(myFILE* stream)
{
    my_fflush(stream);
    return close(stream->fileno);
}
